//
//  XLCatPlateInputView.m
//  XLCarPlateInputViewDemo
//
//  Created by ilongge on 2020/10/21.
//  Copyright © 2020 admin. All rights reserved.
//

#import "XLCarPlateInputView.h"
#import "XLCarPlateInputViewCell.h"
#import "XLCarPlateInputAccessoryView.h"
#import "ResourcesManager.h"

@interface XLCarPlateInputView()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>

@property (nonatomic, strong) XLCarPlateInputAccessoryView *inputAccessoryView;
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, assign) CGSize titleSize;
@property (nonatomic, assign) CGFloat interitemSpacing;
@property (nonatomic, assign) XLCarPlateKeyBoradType keyBoradType;
@property (nonatomic, strong) UIButton *backSpaceButton;
@property (nonatomic, assign) CGFloat backSpaceButtonRight;
@property (nonatomic, strong) XLCarPlateInputViewCell *backSpaceBaseCell;
@end

@implementation XLCarPlateInputView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initSubviews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) { 
        [self parperData];
        [self initSubviews];
    }
    return self;
}


- (void)initSubviews
{
    self.backgroundColor = UIColorFromHex(0xF5F5F5);
    [self configShadow];
    [self configInputAccessoryView];
    [self configCollectionView];
    [self addSubview:self.inputAccessoryView];
    [self addSubview:self.collection];
    [self.collection reloadData];
    [self addSubview:self.backSpaceButton];
}

- (void)parperData
{
    NSArray *dataArray = nil;
    
    NSString *filePath = [[ResourcesManager resourcesBundle] pathForResource:@"XLCarPlateKeyBoardItem"
                                                                      ofType:@"plist"];
    
    NSDictionary *root = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    
    switch (self.keyBoradType) {
        case XLCarPlateKeyBoradTypeProvince:
        {
            dataArray = root[@"province"];
        }
            break;
        case XLCarPlateKeyBoradTypeAbcUppercase:
        case XLCarPlateKeyBoradTypeNumberAbcUppercase:
        {
            dataArray = root[@"code"];
        }
            break;
        default:
            break;
    }
    
    [self.titleArray removeAllObjects];
    [self.titleArray addObjectsFromArray:dataArray];
}

- (void)setCarPlate:(NSString *)carPlate{
    _carPlate = carPlate;
    self.inputAccessoryView.carPlate = carPlate;
}

- (void)showPlateInputView
{
    UIWindow *currentWindow = nil;
    currentWindow = [UIApplication sharedApplication].keyWindow;
    if (currentWindow) {
        [currentWindow addSubview:self];
        [UIView animateWithDuration:0.3
                         animations:^{
            self.transform = CGAffineTransformMakeTranslation(0, - self.frame.size.height);
        }];
    }
}

- (void)hiddenPlateInputView
{
    [UIView animateWithDuration:0.3
                     animations:^{
        self.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}


#pragma mark ************** layout

- (void)layoutSubviews
{
    
    self.collection.frame = CGRectMake(0,
                                       CGRectGetMaxY(self.inputAccessoryView.frame),
                                       self.frame.size.width,
                                       205);
    CGRect rect = [self convertRect:self.backSpaceBaseCell.frame toView:self];
    self.backSpaceButtonRight = CGRectGetMaxX(rect);
    self.backSpaceButton.frame = CGRectMake(self.backSpaceButtonRight-(self.titleSize.width*2+self.interitemSpacing),
                                            CGRectGetMaxY(self.collection.frame)-self.titleSize.height-25,
                                            self.titleSize.width*2+self.interitemSpacing,
                                            self.titleSize.height);
}

#pragma mark configViews

- (void)configShadow
{
    //阴影颜色
    self.layer.shadowColor = UIColorFromHex(0x666666).CGColor;
    //阴影偏移
    self.layer.shadowOffset = CGSizeMake(0, 0 );
    //阴影透明度，默认0
    self.layer.shadowOpacity = 0.3;
    //阴影半径，默认3
    self.layer.shadowRadius = 5;
    
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    
}

- (void)configInputAccessoryView
{
    
    
    WS(weakSelf);
    self.inputAccessoryView.doneButtonBlock = ^(NSString *stringValue) {
        StrongSelf(strongSelf);
        if (strongSelf.doneButtonBlock) {
            strongSelf.doneButtonBlock(stringValue);
        }
    };
    
    self.inputAccessoryView.cancelButtonBlock = ^{
        StrongSelf(strongSelf);
        if (strongSelf.cancelButtonBlock) {
            strongSelf.cancelButtonBlock();
        }
    };
    
    self.inputAccessoryView.specialButtonBlock = ^{
        StrongSelf(strongSelf);
        if (strongSelf.specialButtonBlock) {
            strongSelf.specialButtonBlock();
        }
    };
    
    self.inputAccessoryView.currentSelectIndexBlock = ^(NSInteger integerValue) {
        StrongSelf(strongSelf);
        switch (integerValue) {
            case 0:
                strongSelf.keyBoradType = XLCarPlateKeyBoradTypeProvince;
                break;
            case 1:
                strongSelf.keyBoradType = XLCarPlateKeyBoradTypeAbcUppercase;
                break;
            default:
                strongSelf.keyBoradType = XLCarPlateKeyBoradTypeNumberAbcUppercase;
                break;
        }
        [strongSelf parperData];
        [UIView performWithoutAnimation:^{
            [strongSelf.collection reloadData];
        }];
        
    };
    
}

- (void)backSpaceButtonAction
{
    [self.inputAccessoryView backSpaceAction:self.lockProvince];
}

- (void)configCollectionView
{
    self.titleSize = CGSizeMake(30, 40);
    self.interitemSpacing = (self.frame.size.width - 10 * 30 - 15 * 2) / 10;
    
    UINib *nib = [ResourcesManager nibWith:@"XLCarPlateInputViewCell"];
    [self.collection registerNib:nib forCellWithReuseIdentifier:[[XLCarPlateInputViewCell class] description]];
}

#pragma mark UICollectionViewDelegate / UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    NSInteger count = self.titleArray.count;
    return count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *titiles = self.titleArray[section];
    return titiles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XLCarPlateInputViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[[XLCarPlateInputViewCell class] description]
                                                                              forIndexPath:indexPath];
    if (cell == nil) {
        [collectionView registerNib:[ResourcesManager nibWith:@"WechatSwicthViewCollectionCell"]
         forCellWithReuseIdentifier:[[XLCarPlateInputViewCell class] description]];
        [collectionView dequeueReusableCellWithReuseIdentifier:[[XLCarPlateInputViewCell class] description]
                                                  forIndexPath:indexPath];
    }
    NSArray *titiles = self.titleArray[indexPath.section];
    NSString *titile = titiles[indexPath.row];
    switch (self.keyBoradType) {
        case XLCarPlateKeyBoradTypeAbcUppercase:
        {
            if (indexPath.section == 0) {
                [cell configText:titile andActive:NO];
            }
            else{
                [cell configText:titile andActive:YES];
            }
        }
            break;
        default:
            [cell configText:titile andActive:YES];
            break;
    }
    // 第三行 最后一个
    if (indexPath.section == 2 && indexPath.row == titiles.count-1) {
        self.backSpaceBaseCell = cell;
    }
    
    if (indexPath.section == self.titleArray.count-1 && indexPath.row == titiles.count-1) {
        [self layoutSubviews];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.keyBoradType == XLCarPlateKeyBoradTypeAbcUppercase
        &&
        indexPath.section == 0) {
        
    }
    else{
        NSArray *titiles = self.titleArray[indexPath.section];
        NSString *titile = titiles[indexPath.row];
        if ([SpecilChars isEqualToString:titile ]) {
            return;
        }
        [self.inputAccessoryView insertCode:titile];
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 15, 0, 15);
    switch (section) {
        case 0:
        {
            
        }
            break;
            
        default:
        {
            if (self.keyBoradType == XLCarPlateKeyBoradTypeAbcUppercase
                ||
                self.keyBoradType == XLCarPlateKeyBoradTypeNumberAbcUppercase) {
                
                CGFloat margin = (self.frame.size.width - (self.interitemSpacing * 9 + self.titleSize.width * 9)) / 2.0;
                inset = UIEdgeInsetsMake(0, margin, 0, margin);
            }
            
        }
            break;
    }
    return inset;
}
-(void)dealloc{
    NSLog(@"%s", __func__);
}
#pragma mark 懒加载

- (XLCarPlateInputAccessoryView *)inputAccessoryView
{
    if (_inputAccessoryView == nil) {
        _inputAccessoryView = [[XLCarPlateInputAccessoryView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 95)];
        _inputAccessoryView.backgroundColor = [UIColor whiteColor];
    }
    return _inputAccessoryView;
}

- (UICollectionView *)collection
{
    if (_collection == nil) {
        UICollectionViewFlowLayout *collectionLayOut = [[UICollectionViewFlowLayout alloc] init];
        collectionLayOut.minimumInteritemSpacing = self.interitemSpacing;
        collectionLayOut.headerReferenceSize = CGSizeMake(0, 5);
        collectionLayOut.itemSize = self.titleSize;
        _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,0,0)
                                         collectionViewLayout:collectionLayOut];
        _collection.delegate = self;
        _collection.dataSource = self;
        _collection.backgroundColor = [UIColor clearColor];
    }
    return _collection;
}

- (NSMutableArray *)titleArray
{
    if (_titleArray == nil) {
        _titleArray = [[NSMutableArray alloc] init];
    }
    return _titleArray;
}

-(UIButton *)backSpaceButton
{
    if (_backSpaceButton == nil) {
        _backSpaceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backSpaceButton.backgroundColor = [UIColor whiteColor];
        _backSpaceButton.frame = CGRectMake(0, 0, 100, 40);
        _backSpaceButton.layer.cornerRadius = 5.0;
        _backSpaceButton.clipsToBounds = YES;
        [_backSpaceButton addTarget:self action:@selector(backSpaceButtonAction) forControlEvents:UIControlEventTouchUpInside];
        UIImage *backSpace = [UIImage imageNamed:@"backSpace" inBundle:[ResourcesManager resourcesBundle] compatibleWithTraitCollection:nil];
        [_backSpaceButton setImage:backSpace forState:UIControlStateNormal];
    }
    return _backSpaceButton;
}

@end
